/**
 * 规则管理
 */
var queryRuleSearch = function() {
	var queryRuleFieldSet = new Ext.form.FieldSet({
				id : 'queryRuleFieldSet',
				title : '查询条件',
				collapsible : true,// 可折叠
				buttonAlign : 'center',
				keys : [{
							key : 13, // 13代表回车
							fn : queryRule,
							scope : this
						}],
				items : [{
					layout : 'column',
					border : false,
					items : [{
								columnWidth : .25,
								layout : 'form',
								border : false,
								items : []
							}, {
								columnWidth : .25,
								layout : 'form',
								border : false,
								items : [{
											xtype : 'textfield',
											anchor : '100%',
											fieldLabel : '规则名称',
											name : "ruleName"
										}]
							}, {
								columnWidth : .25,
								layout : 'form',
								border : false,
								items : [{
											xtype : 'dataDictionaryCmb',
											anchor : '100%',
											fieldLabel : "规则类型",
											editable : false,
											autoLoad : false,
											existall : true,
											defaultFirstRow : 1,
											hiddenName : 'ruleType',
											dictionaryType : PmsUtil.rule_type
										}]
							}, {
								columnWidth : .25,
								layout : 'form',
								border : false,
								items : [{
									xtype : 'localcommonbox',
									anchor : '100%',
									fieldLabel : '是否可用',
									editable : false,
									hiddenName : "isEnable",
									loaclarr : [['0', '可用'], ['1', '不可用'],
											['', '全部']],
									value : 0
								}]
							}, {
								columnWidth : .25,
								layout : 'form',
								border : false,
								items : [{
									layout : 'column',
									border : false,
									items : [{
												text : '查询',
												xtype : 'button',
												width : 80,
												handler : function() {
													queryRule();
												},
												style : {
													marginLeft : "100px",
													marginRight : "10px"
												}
											}, {
												text : '重置',
												xtype : 'button',
												width : 80,
												handler : function() {
													queryRuleForm.getForm()
															.reset();
												}
											}]
								}]
							}]
				}]
			});
	fieldSetListeners(
			['queryRuleFieldSet', 'queryRuleForm', 'ruleManagerGrid'], [0.12,
					0.88]);

	var queryRuleForm = new Ext.form.FormPanel({
				id : 'queryRuleForm',
				anchor : '100% 12%',
				frame : true,
				labelAlign : 'right',
				bodyBorder : false,
				items : [queryRuleFieldSet]
			});
	return queryRuleForm;
};

/**
 * grids
 */
var ruleManagerGrid = function() {
	var ruleManagerCm = new Ext.grid.ColumnModel([new Ext.grid.RowNumberer(), {
				dataIndex : "id",
				header : "规则编号",
				sortable : true,
				width : 70
			}, {
				dataIndex : "ruleName",
				header : "规则名称",
				sortable : false,
				width : 70,
				renderer : function(value, meta, record) {
					if (value) {
						meta.attr = 'ext:qtitle="规则名称:" ext:qtip="' + value
								+ '"';
						return value;
					}
				}
			}, {
				dataIndex : "ruleDescribe",
				header : "规则描述",
				sortable : false,
				width : 90,
				renderer : function(value, meta, record) {
					if (value) {
						meta.attr = 'ext:qtitle="规则描述:" ext:qtip="' + value
								+ '"';
						return value;
					}
				}
			}, {
				dataIndex : "ruleType",
				header : "规则类型",
				sortable : false,
				width : 70,
				renderer : function(value) {
					return PmsUtil.RuleType(value);
				}
			}, {
				dataIndex : "limitNumber",
				header : "限制商品个数",
				sortable : false,
				width : 90
			}, {
				dataIndex : "discountNumber",
				header : "商品折扣",
				sortable : false,
				width : 60
			}, {
				dataIndex : "lowLimitMoney",
				header : "最低订单总额",
				sortable : false,
				width : 80,
				renderer : function(value) {
					if (value) {
						return PmsUtil.Price(value);
					}
				}
			}, {
				dataIndex : "benefitMoney",
				header : "优惠金额",
				sortable : false,
				width : 60,
				renderer : function(value) {
					if (value) {
						return PmsUtil.Price(value);
					}
				}
			}, {
				dataIndex : "eachFullMoney",
				header : "每满金额",
				sortable : false,
				width : 60,
				renderer : function(value) {
					if (value) {
						return PmsUtil.Price(value);
					}
				}
			}, {
				dataIndex : "eachFewNumber",
				header : "间隔折扣数",
				sortable : false,
				width : 70
			}, {
				dataIndex : "goodsGiftsGroupId",
				header : "赠品商品组",
				sortable : false,
				width : 70
			}, {
				dataIndex : "priority",
				header : "优先级",
				sortable : false,
				width : 70
			}, {
				dataIndex : "isEnable",
				header : "是否可用",
				sortable : false,
				width : 70,
				renderer : function(value) {
					return PmsUtil.FixingIsEnable(value);
				}
			}, {
				dataIndex : "createdDate",
				header : "创建时间",
				sortable : false,
				width : 130
			}, {
				dataIndex : "createdName",
				header : "创建人",
				sortable : false,
				width : 60
			}, {
				dataIndex : "updatedDate",
				header : "修改时间",
				sortable : false,
				width : 130
			}, {
				dataIndex : "updatedName",
				header : "修改人",
				sortable : false,
				width : 60
			}, {
				header : "管理",
				width : 170,
				dataIndex : "id",
				sortable : false,
				renderer : function(j, i, g, m, h) {
					var l = g.data.id;
					var isEnable = g.data.isEnable;
					var k = "";
					if (isGranted("salesRuleManager_编辑")) {
						k += '&nbsp;&nbsp;<a href="#" onclick="updSalesRule('
								+ l + ",'" + isEnable + "')\" >编辑</a>";
					}
					if (isGranted("salesRuleManager_可用")) {
						if (isEnable == 1) {
							k += '&nbsp;&nbsp;<a href="#" onclick="updIsEnableById('
									+ l
									+ ','
									+ "0"
									+ ','
									+ "'可用'"
									+ ')\" >可用</a>';
						}
					}
					if (isGranted("salesRuleManager_不可用")) {
						if (isEnable == 0) {
							k += '&nbsp;&nbsp;<a href="#" onclick="updIsEnableById('
									+ l
									+ ','
									+ "1"
									+ ','
									+ "'不可用'"
									+ ')\" >不可用</a>';
						}
					}
					if (isGranted("salesRuleManager_商品规格")) {
						k += '&nbsp;&nbsp;<a href="#" onclick="addGoodsPriceSizeToRule('
								+ l + ',1,0)\" >商品规格</a>';
					}
					return k;
				}
			}]);

	// 定义分析器
	var ruleManagerGrid = new Ext.data.JsonReader({
				totalProperty : "totalCount",
				root : "list",
				fields : [{
							name : "id"
						}, {
							name : "ruleName"
						}, {
							name : "ruleDescribe"
						}, {
							name : "ruleType"
						}, {
							name : "discountNumber"
						}, {
							name : "lowLimitMoney"
						}, {
							name : "benefitMoney"
						}, {
							name : "eachFullMoney"
						}, {
							name : "eachFewNumber"
						}, {
							name : "goodsGiftsGroupId"
						}, {
							name : "priority"
						}, {
							name : "isEnable"
						}, {
							name : "createdDate"
						}, {
							name : "createdName"
						}, {
							name : "updatedDate"
						}, {
							name : "updatedName"
						}, {
							name : "limitNumber"
						}]
			});

	// 取数据store
	var ruleViewStore = new Ext.data.Store({
				autoLoad : true,// 要加载数据必须设置为true
				proxy : new Ext.data.HttpProxy({
							url : __ctxPath
									+ "/couponRuleManager/querySalesRule"
						}),
				remoteSort : false,
				baseParams : {
					start : 0,
					limit : 25
				},
				listeners : {
					beforeload : {
						fn : function(thiz, options) {
							Ext.apply(thiz.baseParams, Ext
											.getCmp('queryRuleForm').getForm()
											.getValues());
						}
					}
				},
				reader : ruleManagerGrid
			});

	// 定义grid的toolbar
	var salesRuleTb = new Ext.Toolbar({
				id : "salesRuleTb",
				height : 25,
				items : []
			});
	salesRuleTb.add(new Ext.scm.Button({
				text : "添加规则",
				iconCls : "btn-add",
				width : 80,
				pressed : true,
				hsValue : "salesRlueManager_添加规则",
				listeners : {
					"click" : function() {
						addSalesRlue();
					}
				}
			}));
	salesRuleTb.add(new Ext.Toolbar.Spacer());
	salesRuleTb.add(new Ext.scm.Button({
				text : "刷 新",
				iconCls : "btn-refresh",
				width : 80,
				hsValue : 'salesRlueManager_刷新',
				pressed : true,
				handler : function() {
					queryRule();
				}
			}));
	var ruleManagerGrid = new Ext.grid.GridPanel({
				id : 'ruleManagerGrid',
				tbar : salesRuleTb,
				store : ruleViewStore,
				cm : ruleManagerCm,
				autoScroll : true,
				loadMask : true,
				stripeRows : true,
				columnLines : true,
				loadMask : {
					msg : "正在加载数据，请稍侯……"
				},
				viewConfig : {
					emptyText : '没有您想要的数据!'
				},
				anchor : '100% 88%',
				frame : true,
				bbar : new PG.PagingBar({
							id : 'ruleGridPage',
							store : ruleViewStore
						})
			});
	return ruleManagerGrid;
};

// 查询
function queryRule() {
	if (Ext.getCmp('queryRuleForm').getForm().isValid()) {
		var grid = Ext.getCmp('ruleManagerGrid');
		var store = grid.store;
		var pagesize = Ext.getCmp('ruleGridPage').pageSize;
		store.load({
					params : {
						start : 0,
						limit : pagesize
					}
				});
	}
}

// 添加规则
function addSalesRlue() {
	try {
		saveSalesRlueWin(null, "添加规则", 0).show();
	} catch (Error) {
		Ext.Loader.load([__ctxPath + '/js/rule/salesRuleForm.js'], function() {
					saveSalesRlueWin(null, "添加规则", 0).show();
				});
	}
}

// 修改规则
function updSalesRule(id, isEnable) {
	try {
		saveSalesRlueWin(id, "编辑规则", isEnable).show();
	} catch (Error) {
		Ext.Loader.load([__ctxPath + '/js/rule/salesRuleForm.js'], function() {
					saveSalesRlueWin(id, "编辑规则", isEnable).show();
				});
	}
}

// 修改是否可用
function updIsEnableById(id, isEnable, msg) {
	Ext.Msg.confirm("信息确认", "是否将该规则设为" + msg + "?", function(btn) {
				if (btn == "yes") {
					var optionMask = new Ext.LoadMask(Ext.getBody(), {
								msg : "正在处理,请稍后..."
							});
					optionMask.show();
					Ext.Ajax.request({
								url : __ctxPath
										+ "/couponRuleManager/updIsEnableById",
								params : {
									id : id,
									isEnable : isEnable
								},
								method : "post",
								success : function(response) {
									optionMask.hide();
									var jsonData = Ext.util.JSON
											.decode(response.responseText);
									if (jsonData.success) {
										Ext.MessageBox.show({
													title : "信息提示",
													msg : jsonData.data,
													buttons : Ext.MessageBox.OK,
													icon : Ext.MessageBox.INFO
												});
										queryRule();
									} else {
										Ext.MessageBox.show({
													title : "错误提示",
													msg : jsonData.data,
													buttons : Ext.MessageBox.OK,
													icon : Ext.MessageBox.ERROR
												});
									}
								},
								failure : function(response) {
									optionMask.hide();
									Ext.MessageBox.show({
												title : "操作信息",
												msg : "服务器请求异常,请稍后再试!",
												buttons : Ext.MessageBox.OK,
												icon : Ext.MessageBox.ERROR
											});
								}
							});
				}
			});

}

/**
 * 添加商品规格
 */
function addGoodsPriceSizeToRule(salesRuleId, goodsStatus, isDelete) {
	Ext.Ajax.request({
				url : __ctxPath + "/couponRuleManager/selectGoodsBySalesRuleId",
				method : "POST",
				params : {
					salesRuleId : salesRuleId
				},
				success : function(f, h) {
					var rights = [];
					var funDate = Ext.util.JSON.decode(f.responseText);
					if (funDate != null) {
						// rights = funDate.split(',');
						for (var i = 0; i < funDate.length; i++) {
							var goodsPriceSizeId = funDate[i].goodsPriceSizeId;
							rights.push(goodsPriceSizeId);
						}
					};
					Ext.Loader.load([__ctxPath + '/js/rule/ruleGoodsTree.js'],
							function() {
								saveGoodsRlueTreeWin(salesRuleId, "添加商品规则", rights)
										.show();
							});
				},
				failure : function(f, g) {
					Ext.MessageBox.show({
								title : "操作信息",
								msg : "加载商品规格出错!",
								buttons : Ext.MessageBox.OK,
								icon : Ext.MessageBox.ERROR
							});
				},
				scope : this
			});
}

Ext.getCmp("centerTabPanel").getActiveTab().add(queryRuleSearch(),
		ruleManagerGrid());
Ext.getCmp("centerTabPanel").getActiveTab().doLayout();
